/**
 * Created by Administrator on 2017/8/18 0018.
 */

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const DbUrl='mongodb://localhost:27017/';  /*连接数据库*/
const dbName = 'mydb';


function  __connectDb(callback){


    MongoClient.connect(DbUrl,{ useNewUrlParser: true }, (err, client)=>{

        assert.equal(null, err);
        if(err){

            console.log('数据库连接失败');
            return;
        }

        callback(client);
    })

}

exports.ObjectID = require('mongodb').ObjectID;

exports.find=function(collectionname,json,callback){

    __connectDb(function(client){

        const db = client.db(dbName);
        var result=db.collection(collectionname).find(json);

        result.toArray(function(error,data){

            client.close();
            callback(error,data);
        })

    })

}


exports.insert=function(collectionname,json,callback){

    __connectDb(function(client){

        const db = client.db(dbName);
        db.collection(collectionname).insertOne(json,function(error,data){

            callback(error,data);
        })
    })

}



exports.update=function(collectionname,json1,json2,callback){

    __connectDb(function(client){

        const db = client.db(dbName);
        db.collection(collectionname).updateOne(json1,{$set:json2},function(error,data){

            callback(error,data);
        })
    })

}


exports.deleteOne=function(collectionname,json,callback){

    __connectDb(function(client){

        const db = client.db(dbName);
        db.collection(collectionname).deleteOne(json,function(error,data){
            callback(error,data);
        })
    })

}